'use strict'

import Vue from 'vue'
import axios from 'axios'
import router from '../router'

const baseUrl = 'http://localhost:8999'

let config = {
  baseURL: baseUrl, // 默认
  withCredentials: true, // Check cross-site Access-Control
  timeout: 1000 * 5,
  headers: {}
}

const _axios = axios.create(config)

_axios.interceptors.request.use(
  config => {
    if (localStorage.token) {
      config.headers['Authorization'] = `Bearer ${localStorage.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// Add a response interceptor
_axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        // 如果后端返回没有权限
        case 401:
          // 清除token信息并跳转到登录页面
          localStorage.clear()
          router.replace('/signin')
      }
    }
    return Promise.reject(error.response.data) // 返回接口返回的错误信息
  }
)

// 简单的封装GET方法
const httpGet = (url, params) => {
  return new Promise((resolve, reject) => {
    _axios({
      method: 'GET',
      url,
      params: params
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}

// 简单的封装POST方法
const httpPost = (url, data) => {
  return new Promise((resolve, reject) => {
    _axios({
      method: 'POST',
      url,
      data: data
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}

Plugin.install = function (Vue, options) {
  Vue.axios = _axios
  window.axios = _axios
  Object.defineProperties(Vue.prototype, {
    axios: {
      get () {
        return _axios
      }
    },
    $axios: {
      get () {
        return _axios
      }
    },
    // vue页面,this.$httpGet调用
    $httpGet: {
      get () {
        return httpGet
      }
    },
    $httpPost: {
      get () {
        return httpPost
      }
    }
  })
}

Vue.use(Plugin)

// 在js调用该方法
export const $httpGet = httpGet
export const $httpPost = httpPost

export default Plugin
